﻿using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using FirstFloor.Documents.Annotations;
using FirstFloor.Documents.Annotations.Storage;
using FirstFloor.Documents.Controls;
using FirstFloor.Documents.Search;
using SharpZipLib;

namespace SampleBrowser.Views
{
    public partial class SampleFullTextSearchHighlight : Page
    {
        private AnnotationStore store;
        private Highlight searchHighlight;

        public SampleFullTextSearchHighlight()
        {
            InitializeComponent();

            this.store = new AnnotationStore();

            // create the highlight annotation used to highlight search results
            this.searchHighlight = new Highlight();
            this.store.Add(this.searchHighlight);

            // enable annotation service
            var service = new AnnotationService(this.Viewer);
            service.Enable(this.store);

            // listen for search result collection changes
            this.DataSource.SearchResults.CollectionChanged += SearchResults_CollectionChanged;

            this.Loaded += (o, e) => {
                this.DataSource.PackageReader = new SharpZipPackageReader(new Uri("Assets/Documents/WhitePaper.xps", UriKind.Relative));
            };
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            // properly clears the datasource and closes the package reader
            this.DataSource.PackageReader = null;
        }

        private void DataSource_LoadError(object sender, ErrorEventArgs e)
        {
            new ErrorWindow(e.Error).Show();
        }

        private void DataSource_SearchCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error != null) {
                MessageBox.Show(e.Error.ToString());
            }
        }

        private void SearchResults_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Reset) {
                this.searchHighlight.TextRanges.Clear();
            }
            else if (e.Action == NotifyCollectionChangedAction.Add) {
                foreach (SearchResult result in e.NewItems) {
                    this.searchHighlight.TextRanges.Add(result.Range);
                }
            }
        }
    }
}
